const fs = require('fs')
const path = require('path')
const process = require('child_process')
const express = require('express')
const multiparty = require('multiparty')
const { readChunk } = require('read-chunk')
const fileType = require('file-type')
const RouteBase = require('./../../routeBase')
const cos = require('./../../../services/cos/index')
const router = express.Router()

class ListImages extends RouteBase {
    handle() {
        cos.getBucket({
            Bucket: 'examplebucket-1250000000', /* 填入您自己的存储桶，必须字段 */
            Region: 'COS_REGION',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
            Prefix: 'a/',           /* Prefix表示列出的object的key以prefix开始，非必须 */
        }, (err, data) => {
            console.log(err || data.Contents);
            if (err) {
                this.res.json({ code: -1, msg: 'failed', data: {} })
                return
            }
            this.res.json({
                code: 0,
                msg: 'ok',
                // data: _.map(res.data.infos, 'access_url').filter(function item() {
                //     let extname = String(path.extname(item)).toLowerCase();
                //
                //     // 只返回`jpg/png`后缀图片
                //     return ['.jpg', '.png'].includes(extname);
                // }),
            })
        });
    }
}

class Download extends RouteBase {
    handle() {
        fs.readFile("/data/release/qcloud-applet-album/output/output.jpg","binary",function (error, file, res) {
            if(error) {
                res.end();
            }
            else{
                res.write(file, "binary");
                res.end();
            }
        });
    }
}

class ImageUploader extends RouteBase {
    constructor() {
        super(...arguments);

        // 图片允许上传的最大文件大小，单位(M)
        this.MAX_FILE_SIZE = 5;
    }

    handle() {
        const result = { 'code': -1, 'msg': '', 'data': {} };

        this.parseForm()
            // then前面的执行完了再执行then里面的，files这个对象，看成形参？
            .then(function({ files }){
                if (!('image' in files)) {
                    result.msg = '参数错误';
                    return;
                }
                const imageFile = files.image[0];
                // read a chunk from a file，
                const buffer = readChunk.sync(imageFile.path, 0, 262);
                const resultType = fileType(buffer);
                if (!resultType || !['image/jpeg', 'image/png'].includes(resultType.mime)) {
                    result.msg = '仅jpg/png格式';
                    return;
                }
                let srcpath = imageFile.path;
                process.exec("cp "+srcpath+" /data/release/qcloud-applet-album/upload/upload.jpg");
                process.exec("/data/release/qcloud-applet-album/edges /data/release/qcloud-applet-album/upload/upload.jpg /data/release/qcloud-applet-album/output/output.jpg");
            })
            .catch(e => {
                if (e.statusCode === 413) {
                    result.msg = `单个不超过${this.MAX_FILE_SIZE}MB`;
                } else {
                    result.msg = '图片上传失败，请稍候再试';
                }
            })
            .then(() => {
                this.res.json(result);
            });
    }

    parseForm() {
        const form = new multiparty.Form({
            encoding: 'utf8',
            maxFilesSize: this.MAX_FILE_SIZE * 1024 * 1024,
            autoFiles: true,
            uploadDir: path.join(global.SERVER_ROOT, 'tmp'),
        });

        return new Promise((resolve, reject) => {
            form.parse(this.req, (err, fields = {}, files = {}) => {
                return err ? reject(err) : resolve({ fields, files });
            });
        });
    }
}

class DeleteImage extends RouteBase {
    handle() {
        let filePath = String(this.req.body.filepath || '');

        try {
            filePath = decodeURIComponent(filePath);

            if (!filePath.startsWith(config.cosUploadFolder)) {
                throw new Error('operation forbidden');
            }

        } catch (err) {
            return this.res.json({
                code: -1,
                msg: 'failed',
                data: _.pick(err, ['name', 'message']),
            });
        }
    }
}

router.get('/list', ListImages.makeRouteHandler)
router.get('/download', Download.makeRouteHandler)
router.post('/upload')
router.post('/delete')

module.exports = router
